<?php
/**
 * @return
 * @author 朱乐斌
 * @date
 */

namespace app\api\controller;

use app\api\model\ApplicationModel;
use app\api\model\CourseModel;
use app\api\model\UserGxModel;
use app\api\validate\UserValidate;
use app\Request;
use think\Exception;

class Train extends BaseController
{

    // 获取培训列表
    public function TrainList(Request $request)
    {
        // 查询数据
        $list = CourseModel::select();
        // 返回数据
        return $this->success($list);
    }
    // 报名培训
    public function TrainApply(Request $request)
    {
        // 接收数据
        $data = $request->post();
        try {
            // 查询出这个用户的用户id
            $user = UserGxModel::where('phone',$request->phone)->find();
            // 验证信息是否正确
            validate(UserValidate::class)->scene('course')->check($data);
            // 判断是否多次报名
            $res = ApplicationModel::where('user_id',$user['id'])->where('course_id',$data['course_id'])->find();
            if($res) $this->error('您已经报名过该课程了，请勿重复报名');
            // 存入数据库
            $date = [
                'user_id' => $user['id'],
                'name' => $data['name'],
                'phone' => $data['phone'],
                'course_id' => $data['course_id']
            ];
            $course = new ApplicationModel();
            if ($course->save($date)) $this->success('报名成功');
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }
    // 查看课程详细信息
    public function TrainDetail(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) return errMsg('未知错误');
        $course = CourseModel::where('id', $id)->find();
        $this->success('查询成功', $course);
    }
}